//
//  MBBlConnectViewController.m
//  mZero-iOS
//
//  Created by catch on 16/7/12.
//  Copyright © 2016年 Shenzhen Maker Works Technology Co., Ltd. All rights reserved.
//

#import "MBBlConnectViewController.h"
#import "BLECentralManager.h"
#import "MBRadarView.h"
#import "MBUtils.h"
#import "UIColor+MB.h"
#import "MBBlHelpViewController.h"
#import "MBNotification+MZero.h"
#import "UIView+MB.h"
#import "MBConnectingDotView.h"
#import "MBBLEDeviceListViewController.h"

/**
 *  连接状态
 */
typedef NS_ENUM(NSUInteger,MBBlConnectStatus) {
    /**
     *  默认
     */
    MBBlConnectStatusDeafult,
    /**
     *  蓝牙未开启
     */
    MBBlConnectStatusPowerOff,
    /**
     *  空闲（未有设备靠近）
     */
    MBBlConnectStatusIdle,
    /**
     *  设备靠近
     */
    MBBlConnectStatusConnectClosing,
    /**
     *  开始连接
     */
    MBBlConnectStatusConnecting,
    /**
     *  已连接
     */
    MBBlConnectStatusConnected,
    /**
     *  连接失败
     */
    MBBlConnectStatusConnectFailed,
};

//连接超时时长
static const NSTimeInterval secondsConnectionTimeout = 10;

@interface MBBlConnectViewController ()<BLEControllerDelegate,MBBLEDeviceListViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UIButton *deviceListButton;
@property (weak, nonatomic) IBOutlet UIView *closeView;
@property (weak, nonatomic) IBOutlet UIImageView *closeKitView;
@property (weak, nonatomic) IBOutlet UIView *connectView;
@property (weak, nonatomic) IBOutlet MBRadarView *radarView;
@property (weak, nonatomic) IBOutlet MBConnectingDotView *connectingDotView;
@property (weak, nonatomic) IBOutlet UIImageView *connectedIconView;
@property (weak, nonatomic) IBOutlet UIImageView *connectedRightView;

@property (nonatomic, strong) MBBLEDeviceListViewController* deviceListViewController;

//连接的状态
@property (nonatomic, assign) MBBlConnectStatus connectStatus;
//是否在前端显示着
@property (nonatomic, assign) BOOL isForwordShow;
@property (nonatomic, assign) BOOL isNoFirstLoad;
@property (nonatomic, assign) NSInteger closeStableTime;
@property (nonatomic, assign) NSInteger stableTime;

@end

@implementation MBBlConnectViewController

#pragma mark -- Init

single_implementation(MBBlConnectViewController)

+(void)destoryInstance{
    instance = nil;
}

- (void)dealloc{
    [_connectingDotView stopAnimation];
    [MBNotification removeObserver:self];
}

#pragma mark -- Override Methods

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [[BLECentralManager sharedManager] addDelegate:self];
    [MBNotification addObserver:self selector:@selector(onApplicationBecomeActive) name:UIApplicationDidBecomeActiveNotification];
    [MBNotification addObserver:self selector:@selector(onApplicationResignActive) name:UIApplicationWillResignActiveNotification];
    
    _deviceListButton.titleLabel.font = MFontBlod(IsPhone?14:18);
    
    _statusLabel.textColor = [UIColor colorFromHexString:@"424C58"];
    _statusLabel.font = MFontBlod(IsPhone?15:19);
    [_statusLabel setText:NSLocalizedString(@"ble_close_device", nil)];
    
    if([BLECentralManager sharedManager].currentCentralManagerState == BLECentralDelegateStateCentralManagerPoweredOff){
        self.connectStatus = MBBlConnectStatusPowerOff;
    }else{
        //由于此时UI大小还未定型，所以不能调用idle，避免雷达图显示错误
        //self.connectStatus = MBBlConnectStatusIdle;
        _closeKitView.hidden = YES;
        _connectView.hidden = YES;
        _closeView.hidden = NO;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _isForwordShow = YES;
    
    if(_isNoFirstLoad){
        [self _startBLESearching];
    }
    self.isNoFirstLoad = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    _isForwordShow = NO;
    
    [[BLECentralManager sharedManager] stopScanning];
}

#pragma mark -- Public Methods

-(BOOL)canPush{
    BOOL canPush = !_isForwordShow;
    return canPush;
}

#pragma mark -- Private Methods

/**
 *  启动蓝牙搜索
 */
- (void)_startBLESearching{
    if (!_isForwordShow) {
        return;
    }
    
    if([[BLECentralManager sharedManager] resetScanning]){
        self.connectStatus = MBBlConnectStatusIdle;
    }
}

/**
 *  用户手动关闭蓝牙
 */
-(void)_turnOffBlueTooth{
    self.connectStatus = MBBlConnectStatusPowerOff;
    
    [MBNotification postNotificationName:MBN_SelectedBoardTypeRefreshed object:nil];
    [MBNotification postNotificationName:MBN_MCUDisconnected object:nil];
}

/**
 *  连接超时
 */
- (void)_bleConnectTimeout{
    if(_connectStatus == MBBlConnectStatusConnecting){
        self.connectStatus = MBBlConnectStatusConnectFailed;
    }
}

/**
 *  连接外设
 *
 *  @param peripheral 外设
 */
-(void)_connectTo:(BLEPeripheral *)peripheral{
    if(_connectStatus == MBBlConnectStatusConnecting) return;
    
    [[BLECentralManager sharedManager] disconnectActivePeripheral];
    [[BLECentralManager sharedManager] connectPeripheral:peripheral.activePeripheral];
    self.connectStatus = MBBlConnectStatusConnecting;
    [self performSelector:@selector(_bleConnectTimeout) withObject:nil afterDelay:secondsConnectionTimeout];
}

-(void)_setIdle{
    self.connectStatus = MBBlConnectStatusIdle;
}

#pragma mark -- setters & getters

-(void)setConnectStatus:(MBBlConnectStatus)connectStatus{
    if (_connectStatus == connectStatus) {
        return;
    }
    _connectStatus = connectStatus;
    
    _deviceListButton.hidden = NO;
    _connectedRightView.hidden = YES;
    
    if (connectStatus == MBBlConnectStatusPowerOff){
        _deviceListButton.hidden = YES;
        _closeView.hidden = NO;
        _closeKitView.hidden = YES;
        _connectView.hidden = YES;
        [_statusLabel setText:NSLocalizedString(@"ble_is_not_turned_on", nil)];
        [_radarView stopAnimation];
        
    }else if (connectStatus == MBBlConnectStatusConnectClosing) {
        _closeView.hidden = NO;
        _connectView.hidden = YES;
        _closeKitView.hidden = NO;
        [_statusLabel setText:NSLocalizedString(@"ble_device_found", nil)];
        [_radarView startAnimation];
        
    }else if (connectStatus == MBBlConnectStatusConnecting) {
        _closeView.hidden = YES;
        _connectView.hidden = NO;
        _statusLabel.text = NSLocalizedString(@"ble_connecting", nil);
        _connectedIconView.hidden = YES;
        [_connectingDotView startAnimation];
        [_radarView stopAnimation];
        
    }else if (connectStatus == MBBlConnectStatusConnected) {
        _connectedRightView.hidden = NO;
        _closeView.hidden = YES;
        _connectView.hidden = NO;
        _statusLabel.text = NSLocalizedString(@"ble_connect_success", nil);
        _connectedIconView.hidden = NO;
        _connectedIconView.image = [UIImage imageNamed:@"radar-icon-connect"];
        [_connectingDotView stopAnimation];
        
    }else if (connectStatus == MBBlConnectStatusConnectFailed) {
        _closeView.hidden = YES;
        _connectView.hidden = NO;
        _statusLabel.text = NSLocalizedString(@"ble_connection_failed", nil);
        _connectedIconView.hidden = NO;
        _connectedIconView.image = [UIImage imageNamed:@"radar-icon-disconnected"];
        [_connectingDotView stopAnimation];
        
    }else{//idle
        _closeView.hidden = NO;
        _closeKitView.hidden = YES;
        _connectView.hidden = YES;
        [_statusLabel setText:NSLocalizedString(@"ble_close_device", nil)];
        [_radarView startAnimation];
    }
}

#pragma mark -- IBAction

- (IBAction)backButtonClicked:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    if (sender) {//按了按钮退出界面
        if (_delegate && [_delegate respondsToSelector:@selector(backButtonClicked)]) {
            [_delegate backButtonClicked];
        }
    }
}

- (IBAction)helpButtonClicked:(id)sender {
    MBBlHelpViewController* vc = [[MBBlHelpViewController alloc]init];
    [self presentViewController:vc animated:YES completion:nil];
}

- (IBAction)deviceListButtonClicked:(id)sender {
    _deviceListViewController = [[MBBLEDeviceListViewController alloc]init];
    _deviceListViewController.delegate = self;
    [_deviceListViewController showView];
}

-(void)didSelectPeripheral:(BLEPeripheral *)peripheral{
    if (!peripheral) {
        return;
    }
    [self _connectTo:peripheral];
}

#pragma mark -- NSNotificationCenter

-(void)onApplicationResignActive{
    [[BLECentralManager sharedManager] stopScanning];
}

- (void)onApplicationBecomeActive{
    [self _startBLESearching];
}

#pragma mark -- BLEControllerDelegate

- (void)bleConnected{
    self.connectStatus = MBBlConnectStatusConnected;
    
    [self performSelector:@selector(backButtonClicked:) withObject:nil afterDelay:0.5f];
}

- (void)bleDisconnected{
    self.connectStatus = MBBlConnectStatusIdle;
    
    [MBNotification postNotificationName:MBN_MCUDisconnected object:nil];
    
    //重新扫描蓝牙
    [[BLECentralManager sharedManager] resetScanning];
}

- (void)bleStateChanged{
    if([BLECentralManager sharedManager].currentCentralManagerState == BLECentralDelegateStateCentralManagerPoweredOff){//用户关闭了蓝牙
        [self _turnOffBlueTooth];
        
    }else if([BLECentralManager sharedManager].currentCentralManagerState == BLECentralDelegateStateCentralManagerPoweredOn){//用户开启了蓝牙
        [self _startBLESearching];
    }
}

-(void)blePeripheralRSSIChange:(BLEPeripheral *)peripheral{
    if(!_isForwordShow || _deviceListViewController.isShowing || _connectStatus == MBBlConnectStatusConnecting || _connectStatus == MBBlConnectStatusConnected) return;
    
    if (![peripheral.activePeripheral.name.lowercaseString hasPrefix:@"makeblock"]) {
        return;
    }
    
    NSInteger rssi = [peripheral.RSSI integerValue];
    if (rssi > 0) {
        return;
    }
    
    NSUInteger RSSIConnecting = IsPhone ? 30 : 38;
    NSUInteger RSSIClosing = IsPhone ? 50 : 60;
    
    //是否有设备靠近
    BOOL hasClose = NO;
    for (BLEPeripheral* bean in [BLECentralManager sharedManager].peripherals) {
        NSInteger beanRssi = [bean.RSSI integerValue];
        if (labs(beanRssi) > RSSIConnecting && labs(beanRssi) <= RSSIClosing) {
            hasClose = YES;
        }
    }
    
    //等待其稳定了再改变状态
    if (hasClose) {
        self.closeStableTime++;
        self.stableTime = 0;
        if (_closeStableTime >= 10) {
            self.closeStableTime = 0;
            self.connectStatus = MBBlConnectStatusConnectClosing;
        }
    }else{
        self.closeStableTime = 0;
        self.stableTime++;
        if (self.stableTime >=10) {
            if (self.connectStatus == MBBlConnectStatusConnectFailed) {//失败的话，暂停一秒让用户看到失败的提示
                [self performSelector:@selector(_setIdle) withObject:nil afterDelay:1.0f];
            }else{
                [self _setIdle];
            }
        }
    }
    
    //信号强度在RSSIConnecting左右连接设备
    if (labs(rssi) <= RSSIConnecting) {
        [self _connectTo:peripheral];
    }
}

- (BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

@end
